package com.sentiment.servlet;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.bson.Document;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sentiment.bean.OperationInfo;
import com.sentiment.database.bean.Keyword;
import com.sentiment.database.bean.UserInfo;
import com.sentiment.database.dbUtil.DbUtil;
import com.sentiment.shiro.ActiveUser;
import com.sentiment.tools.Format;

/**
 * Servlet implementation class UserKeywordServlet
 */
@WebServlet("/UserKeywordServlet")
public class UserKeywordServlet extends HttpServlet {
	private static final long serialVersionUID = 85556565656565561L;
       
    public UserKeywordServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
				String methodName = request.getParameter("method");
				try {
					Method method = getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
					method.invoke(this, request, response);
				} catch (Exception e) {
					e.printStackTrace();
				}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
	
	
	/**
	 * 查看用户所有关键词
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void getKeywords(HttpServletRequest request, 
			HttpServletResponse response) throws IOException{

		String jsonStr = "";
		String user_id = "";
		Subject subject = SecurityUtils.getSubject();
		ActiveUser activeUser = (ActiveUser) subject.getPrincipal();
		if(activeUser == null){
			jsonStr = "{\"recordsTotal\":"+ 0 +",\"Info\":" + "\"" + OperationInfo.LoginTimeOut + "\"" +"}";
		}else{
			user_id = activeUser.getUser_id();
			long count = 0;
			UserInfo userinfo = new UserInfo();
			userinfo = userinfo.getUserInfoByUser_id(user_id);
			if(userinfo == null){
				jsonStr = "{\"recordsTotal\":"+ count +",\"Info\":" + "\"" + OperationInfo.NoKeywords + "\"" +"}";
			}else{
				List<String> keywordidList = userinfo.getKeywordList();		
				if(keywordidList != null && keywordidList.size() != 0){
					count = keywordidList.size();				
					List<Keyword> keywordlist = new ArrayList<>();
					DbUtil db = new DbUtil();
					db.openConnection(Keyword.dbName, Keyword.collection);
					for (int i = 0; i < count; i++) {
						Document t = db.query(keywordidList.get(i));
						Keyword keyword = new Keyword(t);
						keywordlist.add(keyword);
					}
					
					ObjectMapper mapper = new ObjectMapper();
					String jsonArr = "";
					try {
						jsonArr = mapper.writeValueAsString(keywordlist);
					} catch (JsonProcessingException e) {
						e.printStackTrace();
					}
					jsonStr = "{\"recordsTotal\":"+ count +",\"keywords\":" + jsonArr+"}";
				}else{
					jsonStr = "{\"recordsTotal\":"+ count +",\"Info\":" + "\"" + OperationInfo.NoKeywords + "\"" +"}";
				}
			}
		}
		
		
		System.out.println(jsonStr);
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(jsonStr);
		
		
	}
	
	/**
	 * 删除一个关键词
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void removeKeyword(HttpServletRequest request, 
			HttpServletResponse response) throws IOException{

		String keyword_id = request.getParameter("keyword_id");
		
		String jsonStr = "";
		String user_id = "";
		Subject subject = SecurityUtils.getSubject();
		ActiveUser activeUser = (ActiveUser) subject.getPrincipal();
		if(activeUser == null){
			jsonStr = "{\"Info\":"+ "\"" + OperationInfo.LoginTimeOut + "\"" +"}";
		}else{
			user_id = activeUser.getUser_id();
			
			//删除 Keyword 表中数据
			DbUtil db = new DbUtil();
			db.openConnection(Keyword.dbName, Keyword.collection);
			Keyword keyword = new Keyword();
			keyword.set_id(keyword_id);
			boolean keywordflag = db.remove(keyword.toDocument_id(), new String[]{"_id"});
			db.closeConnection();
			
			//删除  UserInfo 表中数据				
			UserInfo userinfo = new UserInfo();
			userinfo = userinfo.getUserInfoByUser_id(user_id);
			boolean userinfoflag = true;
			if(userinfo == null){
				userinfoflag = false;
			}else{
				List<String> keywordList = userinfo.getKeywordList();			
				if(keywordList.contains(keyword_id)){
					keywordList.remove(keyword_id);
					userinfo.setKeywordList(keywordList);
					db.openConnection(UserInfo.dbName, UserInfo.collection);
					userinfoflag = db.update(userinfo.toDocument(), new String[]{"user_id"}, userinfo.toDocument(), new String[]{"keywordList"});
					db.closeConnection();
				}
			}
			
			if(keywordflag && userinfoflag){
				jsonStr = "{\"info\":"+ "\"" + OperationInfo.OperSuccess + "\"" +"}"; 
			}else{
				jsonStr = "{\"info\":"+ "\"" + OperationInfo.OperFailure + "\"" +"}"; 
			}
		}
		
		
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(jsonStr);
		
	}
	
	
	/**
	 * 添加一个关键词
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void addKeyword(HttpServletRequest request, 
			HttpServletResponse response) throws IOException {
		
		String keywordStr = request.getParameter("keyword");
		
		String jsonStr = "";
		String user_id = "";
		Subject subject = SecurityUtils.getSubject();
		ActiveUser activeUser = (ActiveUser) subject.getPrincipal();
		if(activeUser == null){
			jsonStr = "{\"Info\":"+ "\"" + OperationInfo.LoginTimeOut + "\"" +"}";
		}else{
			user_id = activeUser.getUser_id();
		
			//向 Keyword 表中插入数据
			DbUtil db = new DbUtil();
			db.openConnection(Keyword.dbName, Keyword.collection);
			Keyword keyword = new Keyword(Format.date2String(new Date(), 3), keywordStr, null);
			String keyword_id = db.insertGetId(keyword.toDocument()).toString();
			db.closeConnection();
			
			//向 UserInfo 表中插入数据				
			UserInfo userinfo = new UserInfo();
			userinfo = userinfo.getUserInfoByUser_id(user_id);
			boolean userinfoflag = true;
			if(userinfo == null){
				userinfoflag = false;
			}else{
				List<String> keywordList = userinfo.getKeywordList();
				if(keywordList == null)
					keywordList = new ArrayList<>();
				keywordList.add(keyword_id);
				userinfo.setKeywordList(keywordList);
				db.openConnection(UserInfo.dbName, UserInfo.collection);
				userinfoflag = db.update(userinfo.toDocument(), new String[]{"user_id"}, userinfo.toDocument(), new String[]{"keywordList"});
				db.closeConnection();
			}
			if(userinfoflag){
				jsonStr = "{\"info\":"+ "\"" + OperationInfo.OperSuccess + "\"" +"}"; 
			}else{
				jsonStr = "{\"info\":"+ "\"" + OperationInfo.OperFailure + "\"" +"}"; 
			}
		}
			
		
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(jsonStr);
		
	}
	
}
